/**
 * 扫描结果,在tbProjectRepos中使用
 * @param origin 默认 code：在codeup内使用，pipeline： 嵌入tb中使用
 */

import React from 'react';
import UILessBuild from '@alife/yunxiao-build';
import BuildResultDialog from 'components/buildResultDialog/loadable';
import LogModal from 'components/compileLogModal';
import utils from 'utils';
import { getCachedRepoValue } from 'utils/repoIdCache';
import { isPre, isVPC } from 'utils/tenant';
import track from 'utils/track';
import { getFeature, getENV } from 'utils/features';
import { navigateOpen } from 'utils/router';

// 点击buildTag每项的埋点 taskNames/trackAction 任务名称和埋点aciton一一对应
import intl from '../../locale';

const buildTrackInfo = {
  taskNames: [
    intl.get({
      id: 'code-assets.components.buildsResultTag.JavaDevelopmentProtocol',
      defaultMessage: 'Java开发规约',
    }),
    intl.get({
      id: 'code-assets.components.buildsResultTag.SensitiveInformationScanning',
      defaultMessage: '敏感信息扫描',
    }),
    intl.get({
      id: 'code-assets.components.buildsResultTag.DependencyPackageVulnerabilityDetection',
      defaultMessage: '依赖包漏洞检测',
    }),
    intl.get({
      id: 'code-assets.components.buildsResultTag.RecommendedCodePatches',
      defaultMessage: '代码补丁推荐',
    }),
    intl.get({
      id: 'code-assets.components.buildsResultTag.SourceCodeVulnerabilityDetection',
      defaultMessage: '源码漏洞检测',
    }),
  ],
  trackAction: [
    'build_tag_p3c',
    'build_tag_security_sensitive',
    'build_tag_security_dependency',
    'build_tag_precfix',
    'build_tag_security_pinpoint',
  ],
};

export default class BuildsResultTag extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      build: {},
      logVisible: false,
      type: 'codeup',
    };
  }

  componentDidMount() {
    const key = getCachedRepoValue('repo_user');
    const hasCache = utils.getCachedData(`codeup-show-pipeline-${key}`);
    if (!hasCache) {
      this.setState({
        type: 'codeup-show',
      });
    }
  }

  closeDialog = () => {
    const { webApp } = this.props;
    if (webApp) {
      webApp.toggleLift(false);
    }

    this.setState({
      visible: false,
      build: {},
    });
  };

  onCodeupBuildClick = (build) => {
    const { webApp } = this.props;
    if (webApp) {
      webApp.toggleLift(true);
    }

    const trackIndex = buildTrackInfo.taskNames.indexOf(build.task_name);
    track({
      action: buildTrackInfo.trackAction[trackIndex],
      page: 'build_tag_page',
      type: '',
      control: '',
    });

    this.setState({
      visible: true,
      build,
    });
  };

  onCodeupLogClick = (build) => {
    const { webApp } = this.props;
    if (webApp) {
      webApp.toggleLift(true);
    }

    this.setState({
      logVisible: true,
      build,
    });
  };

  goFlow = () => {
    const { pathResource, resourceSubject } = window.FORCE;
    const { projectInfo } = this.props;
    const branch =
      resourceSubject.revisionType === 'branch'
        ? resourceSubject.revision
        : projectInfo.default_branch;
    const tpl = {
      type: 'codeup',
      template: { id: pathResource.id, gitHttpURL: projectInfo.http_url_to_repo, branch },
    };
    const url = `https://${isPre ? 'pre-' : ''}flow.aliyun.com/my/new?sourceTpl=${btoa(
      JSON.stringify(tpl),
    )}`;
    navigateOpen(url);
    track({
      action: 'creat_pipeline',
      page: 'Repo-label',
      type: '',
      control: '',
    });
  };

  afterClose = () => {
    const key = getCachedRepoValue('repo_user');
    utils.setCachedData(`codeup-show-pipeline-${key}`, '1');
    this.setState({
      type: 'codeup',
    });
  };

  getType() {
    const { type } = this.state;
    return isVPC ? 'codeup' : type;
  }

  render() {
    const { container, isNeedRestart, ...others } = this.props;
    const { visible, build, logVisible, noPipeline } = this.state;
    const projectId =
      container.projectId || (window.FORCE.pathResource && window.FORCE.pathResource.id);

    if (!getFeature('scan.buildTag.show')) {
      return null;
    }
    if (!projectId) {
      return null;
    }

    return (
      <React.Fragment>
        <UILessBuild
          uiless_config={window.UILessConfig}
          container={{
            afterClose: this.afterClose,
            goFlow: this.goFlow,
            type: this.getType(), // 可选值为 codeup 和 devops，默认值为 codeup
            noPipeline,
            projectId, // 仓库 id
            ...container,
          }}
          hostEnv={getENV()}
          plugin={{
            onCodeupBuildClick: this.onCodeupBuildClick,
            onCodeupLogClick: this.onCodeupLogClick,
          }}
          {...others}
        />

        {logVisible && (
          <LogModal
            isModalOpen={logVisible}
            projectId={projectId}
            build={build}
            closeModal={() => {
              this.setState({
                logVisible: false,
              });
            }}
          />
        )}

        {visible && (
          <BuildResultDialog
            build={build}
            close={this.closeDialog}
            projectId={projectId}
            isNeedRestart={isNeedRestart}
          />
        )}
      </React.Fragment>
    );
  }
}
